const app = require('express')()
const server = require('http').createServer(app)
const wsServer = require('socket.io')(server)
let wsPort = 7600
let clientsLive = []
let clients = null
let serversLive = []
let servers = null

/**
 * 创建websocket服务器
 * @param {Number} options/port 端口号
 * @param {Function} options/onconnect 发生连接时的回调函数
 * @param {Function} options/onmessage 收到信息时的回调函数
 * @param {Function} options/ondisconnect 有连接断开时的回调函数
 */
const createWsServer = (options = {}) => {
  clients = wsServer.of('/clients')
  servers = wsServer.of('/servers')
  // 函数定义 - 客户端群组
  clients.on('connect', SocketIO => {
    console.log('有客户端接入', SocketIO.id)
    clientsLive.push(SocketIO.id)
    options.onconnect && options.onconnect(SocketIO)

    SocketIO.on('message', (data) => {
      console.log('收到信息', SocketIO.id)
      options.onmessage && options.onmessage(data)
    })

    SocketIO.on('disconnect', () => {
      console.log('有客户端断开', SocketIO.id)
      clientsLive = clientsLive.filter(sid => sid != SocketIO.id)
      options.ondisconnect && options.ondisconnect(SocketIO)
    })
  })
  // 函数定义 - 服务端群组
  servers.on('connect', SocketIO => {
    console.log('有服务端接入', SocketIO.id)
    serversLive.push(SocketIO.id)
    options.onconnect && options.onconnect(SocketIO)

    SocketIO.on('message', (data) => {
      console.log('收到信息', SocketIO.id, data)
      clients && clients.emit('message', data)
      options.onmessage && options.onmessage(data)
    })

    SocketIO.on('disconnect', () => {
      console.log('有服务端断开', SocketIO.id)
      serversLive = serversLive.filter(sid => sid != SocketIO.id)
      options.ondisconnect && options.ondisconnect(SocketIO)
    })
  })
  server.listen(wsPort)
}

// 启动服务
const start = (options = {}) => {
  wsPort = options.port || wsPort
  createWsServer(options)
}

// 关闭服务
const stop = () => {
  wsServer.close()
  server.close()
}

// 发送数据
const send = (data) => {
  if (!data) return
  // clients.emit('message', data)
  clients.send(data)
}

// 获取服务器对象
const getServer = () => {
  return wsServer
}

module.exports = {
  getServer,
  start,
  stop,
  send
}
